import Vue from "vue";
import VueI18n from "vue-i18n";
import erdfServer from "erdf-server";
// 默认语言包
import defaultLang from "../zh/zh.json"
import elementEnLocale from "element-ui/lib/locale/lang/en";
import elementZhLocale from "element-ui/lib/locale/lang/zh-CN";
import elementJaLocale from "element-ui/lib/locale/lang/ja";
import zhCN from "vxe-table/lib/locale/lang/zh-CN";
import enUS from "vxe-table/lib/locale/lang/en-US";
import jaJP from "vxe-table/lib/locale/lang/ja-JP";
import locale from "element-ui/lib/locale";

Vue.use(VueI18n);

/**
 * 注册本地基础语言包
 */
const messages = {
  zh: {
    ...zhCN,
    ...elementZhLocale,
  },
  en: {
    ...enUS,
    ...elementEnLocale,
  },
  ja: {
    ...jaJP,
    ...elementJaLocale,
  },
};

// 定义常量来避免硬编码
const LOCALE_CONFIG_URL =
  "/server/business-manufacture/base/LocaleConfig/getLocaleConfigsByModName";
const COMMON_MOD_NAME = [""];

/**
 * 异步获取本地配置信息
 * @param {string} locale - 语言环境标识
 * @returns {Promise<Object>} 返回配置信息的Promise对象
 */
async function getLocalConfig(locale) {
  // 配置语言后缀请求头
  let config = {
    headers: {
      "X-Source": "NoSignIn",
      "Accept-Language": locale,
    },
  };

  try {
    // 尝试发送配置请求并捕获可能的错误
    const res = await erdfServer(config).erdfRequest(
      LOCALE_CONFIG_URL,
      COMMON_MOD_NAME,
      "post"
    );
    return res;
  } catch (e) {
    // 未启用多语言服务，则使用默认语言包
    console.log("未启用多语言服务");
    return defaultLang.zh;
  }
}

/**
 * 异步注册语言包
 */
export async function registerLanguage(lang) {
  let locale = lang || localStorage.getItem("lang") || "zh";
  // 本地存储中有locale,则启用本地存储，否则异步获取指定locale的本地化配置
  // let messages = localStorage.getItem(locale);
  // const languagePack = messages ? messages : await getLocalConfig(locale);

  const languagePack = await getLocalConfig(locale);

  if (messages[locale]) {
    Object.assign(messages[locale], languagePack);
  }

  // 设置当前语言环境的消息
  i18n.setLocaleMessage(locale, messages[locale]);
}

// 创建国际化实例
export const i18n = new VueI18n({
  locale: localStorage.getItem("lang") || "zh",
  messages,
  silentTranslationWarn: true,
});

locale.i18n((key, value) => i18n.t(key, value));

export default { i18n, registerLanguage };
